<?php

namespace app\common\model;

use think\Model;

class Address extends Model
{
    // 添加收货地址
    public function createAddress()
    {
        // 获取参数
        $params = request()->param();
        $user_id = request()->userId;

        // 检测当前是否有默认地址
        $default_address = $this->where(['user_id'=>$user_id, 'is_default'=>1])->find();
        // 当存在默认地址且添加收货地址为默认地址时
        if($default_address && $params['is_default']==1) {
            $default_address->is_default = 0;
            $default_address->save();
        }
        $address = $this->create([
            'user_id'=>$user_id,
            'provinces'=>$params['provinces'],
            'city'=>$params['city'],
            'area'=>$params['area'],
            'address_name'=>$params['address_name'],
            'address_details'=>$params['address_details'],
            'is_default'=>$params['is_default'],
            'zip_code'=>$params['zip_code'],
            'realname'=>$params['realname'],
            'mobile'=>$params['mobile'],
            'email'=>$params['email'],
        ]);
        if (!$address) TApiException();
    }

    // 收货地址列表
    public function addressList()
    {
        $user_id = request()->userId;
        return $this->where(['user_id'=>$user_id])->select();

    }

    // 地址详情
    public function addressDetail()
    {
        $params = request()->param();
        return $this->find($params['id']);

    }

    // 编辑收货地址
    public function updateAddress()
    {
        // 获取参数
        $params = request()->param();
        $user_id = request()->userId;

        // 检测当前是否有默认地址
        $default_address = $this->where(['user_id'=>$user_id, 'is_default'=>1])->find();
        // 当存在默认地址且添加收货地址为默认地址时
        if($default_address && $params['is_default']==1) {
            $default_address->is_default = 0;
            $default_address->save();
        }
        $address = $this->find($params['id']);
        $address->save([
            'user_id'=>$user_id,
            'provinces'=>$params['provinces'],
            'city'=>$params['city'],
            'area'=>$params['area'],
            'address_name'=>$params['address_name'],
            'address_details'=>$params['address_details'],
            'is_default'=>$params['is_default'],
            'zip_code'=>$params['zip_code'],
            'realname'=>$params['realname'],
            'mobile'=>$params['mobile'],
            'email'=>$params['email'],
        ],['id' => 1]);
        if (!$address) TApiException();
    }

}
